package com.znufe.exam.service.h5;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.znufe.exam.domain.Question;
import com.znufe.exam.domain.TextContent;
import com.znufe.exam.domain.enums.ExamPaperTypeEnum;
import com.znufe.exam.domain.h5.H5ExamPaper;
import com.znufe.exam.domain.h5.H5ExamPaperTitleItemObject;
import com.znufe.exam.repository.QuestionMapper;
import com.znufe.exam.repository.h5.H5ExamPaperMapper;
import com.znufe.exam.service.QuestionService;
import com.znufe.exam.service.SubjectService;
import com.znufe.exam.service.TextContentService;
import com.znufe.exam.service.impl.BaseServiceImpl;
import com.znufe.exam.utility.DateTimeUtil;
import com.znufe.exam.utility.JsonUtil;
import com.znufe.exam.utility.ModelMapperSingle;
import com.znufe.exam.viewmodel.admin.exam.ExamPaperTitleItemVM;
import com.znufe.exam.viewmodel.admin.question.QuestionEditRequestVM;
import com.znufe.exam.viewmodel.h5.H5ExamPaperEditRequestVM;
import com.znufe.exam.viewmodel.h5.H5ExamPaperPageRequestVM;
import com.znufe.exam.viewmodel.h5.H5ExamPaperPageVM;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class H5ExamPaperServiceImpl extends BaseServiceImpl<H5ExamPaper> implements H5ExamPaperService {

    protected final static ModelMapper modelMapper = ModelMapperSingle.Instance();
    private final H5ExamPaperMapper h5examPaperMapper;
    private final QuestionMapper questionMapper;
    private final TextContentService textContentService;
    private final QuestionService questionService;
    private final SubjectService subjectService;

    @Autowired
    public H5ExamPaperServiceImpl(H5ExamPaperMapper h5examPaperMapper,
                                  QuestionMapper questionMapper,
                                  TextContentService textContentService,
                                  QuestionService questionService,
                                  SubjectService subjectService) {
        super(h5examPaperMapper);
        this.h5examPaperMapper = h5examPaperMapper;
        this.questionMapper = questionMapper;
        this.textContentService = textContentService;
        this.questionService = questionService;
        this.subjectService = subjectService;
    }


    @Override
    public PageInfo<H5ExamPaper> page(H5ExamPaperPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageNum(), requestVM.getPageSize(),
                "id desc").doSelectPageInfo(() ->
                h5examPaperMapper.page(requestVM));
    }

    @Override
    public PageInfo<H5ExamPaper> taskExamPage(H5ExamPaperPageRequestVM requestVM) {
        return PageHelper.startPage(requestVM.getPageNum(), requestVM.getPageSize(),
                "id desc").doSelectPageInfo(() ->
                h5examPaperMapper.taskExamPage(requestVM));
    }

    @Override
    public PageInfo<H5ExamPaper> studentPage(H5ExamPaperPageVM requestVM) {
        return PageHelper.startPage(requestVM.getPageNum(), requestVM.getPageSize(),
                "id desc").doSelectPageInfo(() ->
                h5examPaperMapper.studentPage(requestVM));
    }


//    @Override
//    @Transactional
//    public H5ExamPaper savePaperFromVM(H5ExamPaperEditRequestVM h5examPaperEditRequestVM, User user) {
//        ActionEnum actionEnum = (h5examPaperEditRequestVM.getId() == null) ? ActionEnum.ADD : ActionEnum.UPDATE;
//        Date now = new Date();
//        List<H5ExamPaperTitleItemVM> titleItemsVM = h5examPaperEditRequestVM.getTitleItems();
//        List<H5ExamPaperTitleItemObject> frameTextContentList = frameTextContentFromVM(titleItemsVM);
//        String frameTextContentStr = JsonUtil.toJsonStr(frameTextContentList);
//
//        H5ExamPaper h5examPaper;
//        if (actionEnum == ActionEnum.ADD) {
//            h5examPaper = modelMapper.map(h5examPaperEditRequestVM, H5ExamPaper.class);
//            TextContent frameTextContent = new TextContent(frameTextContentStr, now);
//            textContentService.insertByFilter(frameTextContent);
//            h5examPaper.setFrameTextContentId(frameTextContent.getId());
//            h5examPaper.setCreateTime(now);
//            h5examPaper.setCreateUser(user.getId());
//            h5examPaper.setDeleted(false);
//            h5examPaperFromVM(h5examPaperEditRequestVM, h5examPaper, titleItemsVM);
//            h5examPaperMapper.insertSelective(h5examPaper);
//        } else {
//            h5examPaper = h5examPaperMapper.selectByPrimaryKey(h5examPaperEditRequestVM.getId());
//            TextContent frameTextContent = textContentService.selectById(h5examPaper.getFrameTextContentId());
//            frameTextContent.setContent(frameTextContentStr);
//            textContentService.updateByIdFilter(frameTextContent);
//            modelMapper.map(h5examPaperEditRequestVM, h5examPaper);
//            h5examPaperFromVM(h5examPaperEditRequestVM, h5examPaper, titleItemsVM);
//            h5examPaperMapper.updateByPrimaryKeySelective(h5examPaper);
//        }
//        return h5examPaper;
//    }

    @Override
    public H5ExamPaperEditRequestVM examPaperToVM(Integer id) {
        H5ExamPaper h5examPaper = h5examPaperMapper.selectByPrimaryKey(id);
        H5ExamPaperEditRequestVM vm = modelMapper.map(h5examPaper, H5ExamPaperEditRequestVM.class);
        vm.setLevel(h5examPaper.getGradeLevel());

        TextContent frameTextContent = textContentService.
                selectById(h5examPaper.getFrameTextContentId());
        List<H5ExamPaperTitleItemObject> examPaperTitleItemObjects = JsonUtil.toJsonListObject(
                frameTextContent.getContent(), H5ExamPaperTitleItemObject.class);

        List<Integer> questionIds = examPaperTitleItemObjects.stream()
                .flatMap(t -> t.getQuestionItems().stream()
                        .map(q -> q.getId()))
                .collect(Collectors.toList());
        List<Question> questions = questionMapper.selectByIds(questionIds);

        List<ExamPaperTitleItemVM> examPaperTitleItemVMS = examPaperTitleItemObjects
                .stream().map(t -> {
                    ExamPaperTitleItemVM tTitleVM = modelMapper.map(t, ExamPaperTitleItemVM.class);
                    List<QuestionEditRequestVM> questionItemsVM = t.getQuestionItems().stream().map(i -> {
                        Question question = questions.stream()
                                .filter(q -> q.getId().equals(i.getId())).findFirst().get();
                        QuestionEditRequestVM questionEditRequestVM = questionService
                                .getQuestionEditRequestVM(question);
                        questionEditRequestVM.setItemOrder(i.getItemOrder());
                        return questionEditRequestVM;
                    }).collect(Collectors.toList());
                    tTitleVM.setQuestionItems(questionItemsVM);
                    return tTitleVM;
                }).collect(Collectors.toList());

        //vm.setTitleItems(examPaperTitleItemVMS);
        //vm.setScore(ExamUtil.scoreToVM(examPaper.getScore()));
        vm.setScore(h5examPaper.getScore());
        if (ExamPaperTypeEnum.TimeLimit == ExamPaperTypeEnum.fromCode(h5examPaper.getPaperType())) {
            List<String> limitDateTime = Arrays.asList(
                    DateTimeUtil.dateFormat(h5examPaper.getLimitStartTime()),
                    DateTimeUtil.dateFormat(h5examPaper.getLimitEndTime()));
            vm.setLimitDateTime(limitDateTime);
        }
        return vm;
    }

    @Override
    public List<H5ExamPaper> getExamPaperListById(List<Integer> ids) {
        return h5examPaperMapper.getExamPaperListById(ids);
    }

    @Override
    public List<H5ExamPaper> getAllExamPaperListById(List<Integer> ids) {
        return h5examPaperMapper.getAllExamPaperListById(ids);
    }
}
